let mysql = require("mysql");
let formidable = require("formidable");
let express = require("express");
let app = express();
let cookie = require("cookie-parser");
let server = require("http").Server(app);
let io = require('socket.io')(server);
app.use(express.static("node_modules"));
app.use(express.static("style"));
app.set("view engine", "ejs");
app.set("views", "views");
app.use(cookie());

let connection = mysql.createConnection({
  host: "localhost", 
  user: "root",
  password: "root",
  database: "good",
});
connection.connect();
let a = [];
let b = "";
let c = "";

app.get("/", function (req, res) {
  res.render("lts", { data: req.cookies.name });
  res.end();
});

app.get("/login", function (req, res) {
  res.render("login");
  res.end();
});

app.get("/lsjl", function (req, res) {
  // a.forEach(function (e) {
  //   c += e + '<br />';
  // });
  // console.log(c);
  res.render("lsjl", { data: a });
  res.end();
});

app.post("/dologin", function (req, res) {
  let form = new formidable.IncomingForm();
  form.parse(req, function (err, fields) {
    let username = fields.username;
    let password = fields.password;
    let sql = "select * from users where username='" + username + "'";
    connection.query(sql, function (error, results) {
      if (results.length > 0) {
        // console.log("账号正确");
        if (results[0].password == password) {
          // console.log("密码正确");
          res.cookie("name", username, { maxAge: 9000000, httpOnly: true });
          res.redirect("/");
        } else {
          // console.log("密码错误");
          res.redirect("/login");
        }
      } else {
        // console.log("账号不对");
        res.redirect("/login");
      }
      res.end();
    });
  });
});


server.listen(8090);

io.on('connection', function (socket) {
  socket.on('gyf', function (data) {
    // console.log(data);
    socket.broadcast.emit('gyf', data);
   
    if (data.xinxi != undefined) {
      b = data.username + ':' + data.xinxi;
      a.push(b);
      // console.log(a);
    }
  });
});